import 'dart:async';
import 'dart:typed_data';

import 'package:aichat_flutter_wallet/module/module_news/model/news_detail_model.dart';
import 'package:aichat_flutter_wallet/module/module_news/model/remark_item.dart';
import 'package:aichat_flutter_wallet/module/module_news/provider/news_provider.dart';
import 'package:aichat_flutter_wallet/module/module_news/utils/news_util.dart';
import 'package:aichat_flutter_wallet/module/module_news/widget/new_detail_remark_h1.dart';
import 'package:aichat_flutter_wallet/module/module_news/widget/news_detail_header.dart';
import 'package:aichat_flutter_wallet/module_common/network/http_api.dart';
import 'package:aichat_flutter_wallet/module_common/utils/colors.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/image/public_image.dart';
import 'package:aichat_flutter_wallet/module_common/widgets/public_tip/public_tip.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_network/http_manager.dart';
import 'package:lib_network/lib_network.dart';
import 'package:lib_util/lib_util.dart';

import '../../../kai_print.dart';
import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/widgets/header/page_integral_header.dart';
import '../widget/new_commemt_widget.dart';

class NewsDetailPage extends StatefulWidget {
  int target_type;
  String id;
  Function? onClose;
  // 525409958110021 , 1, 1709805822084
  NewsDetailPage({Key? key, this.target_type = 1, this.id = '525409958110021',this.onClose})
      : super(key: key);

  @override
  NewsDetailState createState() => NewsDetailState();
}

class NewsDetailState extends State<NewsDetailPage>
    with AutomaticKeepAliveClientMixin {
  late StreamSubscription walletSubscription;
  late StreamSubscription walletSubscription2;
  NewsDetailModel? newsDetailModel;
  int page = 1;
  int size = 10;
  int allCount = 0;
  bool isEnd = false;
  bool isLoaded = false;
  Uint8List? videoImg;

  getDetail() async {
    try {
      BaseResp? value = await HttpManager().get(API.getNewsDetail,
          {'id': widget.id, "data_type": widget.target_type});
      if (value!.code == 0) {
        NativeChannelBridge().flGoCommentSuccess(widget.target_type.toString(),widget.id.toString(),'views');
        var res = value.data;
        res['id'] = widget.id;
        newsDetailModel = NewsDetailModel.fromJson(res);
        isLoaded = true;
        newsProvider.setDetail(newsDetailModel!);
        if (newsDetailModel!.videos.isNotEmpty) {
          videoImg = await NewsUtil.getVideoThumb(newsDetailModel!.videos[0]);
        }
        setState(() {});
      }
    } catch (e) {}
    ;
  }

// 分享上报
  doShare() {
    try{
      NativeChannelBridge().flGoCommentSuccess(widget.target_type.toString(),widget.id.toString(),'forward').then((value) {
        if(value=='1'){
          newsDetailModel!.shares += 1;
        }
        if(mounted)setState(() {
        });
      }).catchError((_){
        if(mounted)setState(() {});
      });
    }catch(e){
      kaiPrint('${e.toString()}！');
    }
  }

  // 点赞，取消点赞
  doLike() {
    newsProvider.doLike(
        target_id: widget.id,
        target_type: widget.target_type,
        like_status: newsDetailModel!.like_status,
        beforeCall: (value) {
          if (value) {
            newsDetailModel!.likes -= 1;
            newsDetailModel!.like_status = 1;
          } else {
            newsDetailModel!.likes += 1;
            newsDetailModel!.like_status = 0;
          }
          setState(() {});
        },
        failCall: (value) {
          if (value) {
            newsDetailModel!.likes += 1;
            newsDetailModel!.like_status = 0;
          } else {
            newsDetailModel!.likes -= 1;
            newsDetailModel!.like_status = 1;
          }
          setState(() {});
        });
  }

  // 评论
  docomment({String? content, List<String>? videos, List<String>? images}) {
    newsProvider.doComment(
        images: images ?? [],
        videos: videos ?? [],
        target_type: widget.target_type,
        article_id: widget.id,
        content: content ?? '',
        success: (value) {
          kaiPrint('value--one-comment===${value.data['comment']}');
          if (value!.code == 0) {
            Toast.show(context, message: 'Reply successful');
            RemarkItem valueItem = RemarkItem.fromJson(value.data['comment']);
            newsProvider.addOneRemarkList(valueItem);
            newsDetailModel!.comments += 1;
            allCount++;
            NativeChannelBridge().flGoCommentSuccess(widget.target_type.toString(),widget.id.toString(),'comment');
            setState(() {});
          }
        },
        fail: (error) {
          Toast.show(context,
              message: 'Network error, sending failure', status: '2');
        });
  }

  // 获取评论列表
  getCommentList() {
    kaiPrint("{article_id: ${widget.id},target_type: ${widget.target_type},page: ${page},size: ${size},target_id: ''}");
    HttpManager().post(API.getCommentList, {
      'article_id': widget.id,
      "target_type": widget.target_type,
      'page': page,
      'size': size,
      "target_id": ''
    }).then((value) {
      if (value!.code == 0) {
        if (value.data['comment_list'].isNotEmpty) {
          var list = List.from(value.data['comment_list']);
          kaiPrint('list===${list}');
          List<RemarkItem> allCommentList = [];
          list.forEach((element) {
            RemarkItem remarkItem = RemarkItem.fromJson(element);
            allCommentList.add(remarkItem);
          });
          newsProvider.setRemarkList(allCommentList);
        }
        allCount = value.data['count'];
        setState(() {});
      }
    });
  }

  late NewsProvider newsProvider;

  @override
  void initState() {
    super.initState();
    newsProvider = context.read<NewsProvider>();
    initPage();
    // 初始化 页面 参数
    walletSubscription = eventBus.on<GoBackEvent>().listen((event) {
      NativeChannelBridge.instance.closeFlutterPage(num:1);
      if(widget.onClose != null){
        widget.onClose!();
      }
    });    // 初始化 页面 参数
    walletSubscription2 = eventBus.on<GoShareSuccess>().listen((event) {
      // NativeChannelBridge.instance.closeFlutterPage(num:1);
      // if(widget.onClose != null){
      //   widget.onClose!();
      // }
      // 分享成功
      if(event.data=='1'){
        newsDetailModel!.shares += 1;
        if(mounted)setState(() {
        });
      }

    });
  }

  void initPage({
    int? target_type,
    String? id,
}){
    if(target_type!=null&&id!=null){
      widget.target_type = target_type;
      widget.id = id;
    }
    newsProvider.setRemarkListNone();
    newsProvider.setTargetType(widget.target_type,widget.id);
    getDetail();
    getCommentList();
  }

  @override
  void dispose() {
    /// 取消路由订阅
    super.dispose();
    walletSubscription.cancel();
    walletSubscription2.cancel();
  }


  Widget JiuGongGe(List<String> images){
    if(images.isEmpty){
      return SizedBox(height: 0,);
    }
    int crossAxisCount= 3;
    double containerHeight= 360.w;
    int length = images.length;
    if(1<=length && length<=3){
      containerHeight= 120.w;
    }else if (3<length && length<=6) {
      containerHeight = 240.w;
    }else if(6<length && length<=9){
      containerHeight = 360.w;
    }
    return Container(
      width: double.infinity,
      height: containerHeight,
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        padding: EdgeInsets.zero,
        crossAxisSpacing: crossAxisCount !=1? 5.w : 0.w, // 水平方向上的间距
        mainAxisSpacing: crossAxisCount !=1? 5.w : 0.w,
        crossAxisCount: crossAxisCount, // 每行显示的列数
        children: List.generate(
          images.length,
              (index) {
            return InkWell(
              splashColor: Colors.transparent,
              onTap: () {
                NativeChannelBridge().flPreviewMedia(type: 'image',index: index.toString(),datas: images);
                kaiPrint(' ¥「」 ${index}');
              },
              child: Container(
                child: ClipRRect(
              borderRadius: BorderRadius.circular(10.w),
                  child: PublicImage(
                  image: images[index],
                  width: double.infinity,
                  height: double.infinity,
                ),
              ),
            )
            );
          },
        ),
      )
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return WillPopScope(
      onWillPop: () async {
        // 处理返回手势触发的操作
        print('Back button pressed');
        NativeChannelBridge.instance.closeFlutterPage(num:1);
        if(widget.onClose != null){
          widget.onClose!();
        }
        // 返回 true 表示允许执行返回操作，返回 false 表示阻止返回操作
        return true;
      },
      child: Scaffold(
          backgroundColor: Colors.white,
          appBar: PageIntegralCom(
            title: 'Particulars',
            bgColor: Colors.white,
            // 分享
            goShare: () {
              try{
                NativeChannelBridge().flGoCommentSuccess(widget.target_type.toString(),widget.id.toString(),'share').then((value) {
                  if(value=='1'){
                    newsDetailModel!.shares += 1;
                  }
                  if(mounted)setState(() {
                  });
                }).catchError((_){
                  if(mounted)setState(() {});
                });
              }catch(e){
                kaiPrint('failed ！${e.toString()}');
              }
              //  弹出 弹窗
            },
            definedGoBack: true,
            // 返回上一页
            goBack: () {
              NativeChannelBridge.instance.closeFlutterPage(num:1);
              if(widget.onClose!=null){
                widget.onClose!();
              }
            },
            rankBtn:false,
            goRank: () {},
          ),
          body: Center(
              child: Container(
                  margin: EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom),
                  child: ListView.builder(
                      itemCount: newsProvider.remark_item_list.length + 1,
                      padding: EdgeInsets.zero,
                      addAutomaticKeepAlives: false,
                      addRepaintBoundaries: false,
                      itemBuilder: (context, index) {
                        if (!isLoaded) return null;
                        if (index == 0) {
                          return Container(
                            padding: EdgeInsets.only(
                                left: 20.w,
                                right: 20.w,
                                top: 15.h,
                                bottom: 15.h),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                NewsDetailHeader(
                                  newsDetailModel: newsDetailModel!,
                                  target_type: widget.target_type,
                                ),
                                Visibility(
                                    visible: ['1','2'].contains(widget.target_type.toString())&&newsDetailModel!.title!.isNotEmpty,
                                    child: Column(
                                      children: [
                                        SizedBox(
                                          height: 20.w,
                                        ),
                                        Text(
                                          newsDetailModel!.title!,
                                          style: TextStyle(fontSize: 20.sp, color: AppColors.c_333333),
                                        ),
                                      ],
                                    )),
                                SizedBox(height: 15.w),
                                Text(
                                  '${newsDetailModel != null ? newsDetailModel!.content : ''}',
                                  style: TextStyle(
                                      fontSize: 14.sp,
                                      color: AppColors.c_333333),
                                ),
                                SizedBox(height: 10.w),
                                Visibility(
                                    visible: newsDetailModel!.images.isNotEmpty,
                                    child: JiuGongGe(newsDetailModel!.images)),
                                if (newsDetailModel!.videos.isNotEmpty &&
                                    videoImg != null)
                                  newsProvider.getVideoWidget(
                                      videoImg: videoImg!,
                                      callback: () {
                                        NativeChannelBridge().flPreviewMedia(type: 'video',index: 0.toString(),datas: newsDetailModel!.videos);
                                      }),
                                SizedBox(
                                  height: 12.w,
                                ),
                                Row(
                                  children: [
                                    Expanded(
                                      flex: 1,
                                      child: InkWell(
                                        splashColor: Colors.transparent,
                                        onTap: () {
                                          doLike();
                                        },
                                        child: Row(
                                          children: [
                                            PublicImage(
                                              image: (newsDetailModel!
                                                  .like_status ==
                                                  0)
                                                  ? 'assets/images/common/news_like_active.png'
                                                  : 'assets/images/common/news_like.png',
                                              height: 16.w,
                                              width: 16.w,
                                            ),
                                            SizedBox(
                                              width: 5.w,
                                            ),
                                            Text(
                                              '${newsDetailModel!.likes}',
                                              style: TextStyle(
                                                  fontSize: 12.sp,
                                                  color:
                                                  AppColors.c_868391),
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 1,
                                      child: InkWell(
                                        splashColor: Colors.transparent,
                                        onTap: () {
                                          doShare();
                                        },
                                        child: Row(
                                          children: [
                                            PublicImage(
                                              image:
                                              'assets/images/common/news_share.png',
                                              height: 16.w,
                                              width: 16.w,
                                            ),
                                            SizedBox(
                                              width: 5.w,
                                            ),
                                            Text(
                                              newsDetailModel != null
                                                  ? '${newsDetailModel!.shares}'
                                                  : '0',
                                              style: TextStyle(
                                                  fontSize: 12.sp,
                                                  color:
                                                  AppColors.c_868391),
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 1,
                                      child: InkWell(
                                        splashColor: Colors.transparent,
                                        onTap: () {
                                          NewsUtil.showCommentDialog(
                                              ctx: context,
                                              toName : '',
                                              success: (CommemtTypeCallBackData value) {
                                                kaiPrint(
                                                    'showCommentDialog  ----- ===${value}');
                                                docomment(
                                                    content: value.content,
                                                    videos: value.videos,
                                                    images: value.images);
                                              });
                                        },
                                        child: Row(
                                          children: [
                                            PublicImage(
                                              image:
                                              'assets/images/common/news_remark.png',
                                              height: 16.w,
                                              width: 16.w,
                                            ),
                                            SizedBox(
                                              width: 5.w,
                                            ),
                                            Text(
                                              newsDetailModel != null
                                                  ? '${newsDetailModel!.comments}'
                                                  : '0',
                                              style: TextStyle(
                                                  fontSize: 12.sp,
                                                  color:
                                                  AppColors.c_868391),
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      flex: 1,
                                      child: InkWell(
                                        splashColor: Colors.transparent,
                                        onTap: () {
                                        },
                                        child: Row(
                                          children: [
                                            PublicImage(
                                              image:
                                              'assets/images/common/news_see.png',
                                              height: 16.w,
                                              width: 16.w,
                                            ),
                                            SizedBox(
                                              width: 5.w,
                                            ),
                                            Text(
                                              newsDetailModel != null
                                                  ? '${newsDetailModel!.views}'
                                                  : '0',
                                              style: TextStyle(
                                                  fontSize: 12.sp,
                                                  color:
                                                  AppColors.c_868391),
                                            )
                                          ],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                                SizedBox(
                                  height: 20.w,
                                ),
                                Container(
                                  height: 1,
                                  width: double.infinity,
                                  color: AppColors.c_E0E0E0,
                                ),
                              ],
                            ),
                          );
                        } else {
                          if (newsProvider.remark_item_list.isNotEmpty) {
                            if (index - 1 >= allCount) {
                              return null;
                            }
                            if (index - 1 <
                                newsProvider.remark_item_list.length) {
                              return Padding(
                                padding: const EdgeInsets.symmetric(
                                    horizontal: 20),
                                child: NewDetailRemarkH1(
                                    doCommentSuccess: (){
                                      newsDetailModel!.comments += 1;
                                      setState(() {});
                                    },
                                    article_id: newsDetailModel!.id,
                                    key: ValueKey(newsProvider
                                        .remark_item_list[index - 1].id),
                                    item: newsProvider
                                        .remark_item_list[index - 1]),
                              );
                            }

                            if (index - 1 >=
                                newsProvider.remark_item_list.length &&
                                index - 1 < allCount) {
                              page += 1;
                              getCommentList();
                            }
                          }
                        }
                      })))
      ),
    );

  }

  getWordWidget({required String text, VoidCallback? callback}) {
    return Container(
      alignment: Alignment.center,
      width: double.infinity,
      child: InkWell(
        onTap: () {
          if (callback != null) {
            callback();
          }
        },
        child: Text(
          text,
          style: TextStyle(color: AppColors.c_8667FE, fontSize: 12),
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
